package com.gravata.enigma.importer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.gravata.enigma.R;
import com.gravata.enigma.ReloadDataListener;

public class ParseSats extends AsyncTask<String, String, Boolean> {

	private Context context;
	private ProgressDialog progress;
	private ReloadDataListener listener;
	private List<Sat> satelites=new ArrayList<Sat>();
	private final String URL="http://www.portaleds.com/satelites/";

	public ParseSats(Context context,ReloadDataListener listener){
		this.context=context;
		this.listener=listener;
	}

	@Override
	protected Boolean doInBackground(String... arg0) {
		try {

			Document doc=Jsoup.connect(URL).header("Accept-Encoding", "gzip, deflate")
				    .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0")
				    .maxBodySize(0)
				    .timeout(600000)
				    .get();

			Elements options= doc.select("select[name=sat]").first().select("option");

			for(Element option:options){
				String id=option.attr("value");
				String nome=option.text();
				Sat sat=new Sat();
				sat.setNome(nome);
				sat.setPosicao(Integer.parseInt(id));
				satelites.add(sat);
			}

			listener.onFealoadData(satelites);

			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

	}

	@Override
	protected void onPreExecute() {
		progress = new ProgressDialog((Activity) context);
		// Cria novo um ProgressDialogo e exibe
		progress.setMessage(context.getString(R.string.carregando_satelites) + "\n\nURL: "+URL);
		progress.setCancelable(false);
		progress.show();
	}

	@Override
	protected void onProgressUpdate(String... values) {
		// Atualiza mensagem
		if (progress != null)
			progress.setMessage(values[0]);
	}

	@Override
	protected void onPostExecute(Boolean result) {
		progress.dismiss();
	}


}